package com.it.schoolbookshop_back.utils;

import lombok.Data;

/**
 * 用户上下文工具类，用于存储和获取当前登录用户信息
 */
public class UserContext {
    @Data
    public static class UserInfo {
        private Integer userId;
        private String username;
        private String role;
        private String realName;
        
        public UserInfo(Integer userId, String username, String role, String realName) {
            this.userId = userId;
            this.username = username;
            this.role = role;
            this.realName = realName;
        }
    }
    
    private static final ThreadLocal<UserInfo> userHolder = new ThreadLocal<>();
    
    /**
     * 设置用户信息
     */
    public static void setUser(UserInfo userInfo) {
        userHolder.set(userInfo);
    }
    
    /**
     * 设置用户信息
     */
    public static void setUser(Integer userId, String username, String role, String realName) {
        setUser(new UserInfo(userId, username, role, realName));
    }
    
    /**
     * 获取用户信息
     */
    public static UserInfo getUser() {
        return userHolder.get();
    }
    
    /**
     * 获取用户ID
     */
    public static Integer getUserId() {
        UserInfo userInfo = getUser();
        return userInfo != null ? userInfo.getUserId() : null;
    }
    
    /**
     * 获取用户名
     */
    public static String getUsername() {
        UserInfo userInfo = getUser();
        return userInfo != null ? userInfo.getUsername() : null;
    }
    
    /**
     * 获取用户角色
     */
    public static String getRole() {
        UserInfo userInfo = getUser();
        return userInfo != null ? userInfo.getRole() : null;
    }
    
    /**
     * 获取用户真实姓名
     */
    public static String getRealName() {
        UserInfo userInfo = getUser();
        return userInfo != null ? userInfo.getRealName() : null;
    }
    
    /**
     * 清除用户信息
     */
    public static void clear() {
        userHolder.remove();
    }
} 